const Koa = require('koa')
const KoaRouter = require('@koa/router')
const KoaBodyParser = require('koa-bodyparser')
let { userList } = require('./mock')
const app = new Koa();
const router = new KoaRouter();
app.use(KoaBodyParser());
app.use(router.allowedMethods()).use(router.routes())
app.listen(7000, () => console.log('server is running at port 7000 !!'))


router.post('/login', ctx => {
  const { username, password } = ctx.request.body;
  const isUser = userList.find(v => v.username === username && v.password === password)
  if(isUser) {
    ctx.body = {
      code: 200,
      message: '登录成功， 欢迎用户' + isUser.nickname,
      data: isUser
    }
  } else {
    ctx.body = {
      code: 400,
      message: '账户密码错误'
    }
  }
})


router.get('/user/list', ctx => {
  ctx.body = {
    code: 200,
    message: '数据获取成功',
    data: userList.filter(v => v.role !== 'admin')
  }
})


router.delete('/user/list/:id', ctx => {
  const { id } = ctx.request.params;

  userList = userList.filter(v => v.id !== id);

  ctx.body = {
    code: 200
  }
})